package com.bbcare.followup.plat.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.bbcare.comm.AppException;
import com.bbcare.comm.ToolUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.department.plat.service.impl.DepartmentBasicService;
import com.bbcare.followup.plat.dto.bo.PtUserSharePhotoBO;
import com.bbcare.followup.plat.dto.request.PtUserSharePhotoAddReqDTO;
import com.bbcare.followup.plat.dto.request.PtUserSharePhotoQueryReqDTO;
import com.bbcare.followup.plat.dto.response.PtUserSharePhotoResDTO;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.entity.PtUserSharePhoto;
import com.bbcare.followup.plat.service.IMessageNotifyRecordService;
import com.bbcare.followup.plat.service.IPtUserSharePhotoService;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;
import com.bbcare.followup.plat.store.ibatis.IPtUserSharePhotoDao;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 分享照片记录
 */
@Service
@Transactional
public class PtUserSharePhotoServiceImpl implements IPtUserSharePhotoService {
    private static final Log logger = LogFactory.getLog(PtUserSharePhotoServiceImpl.class);
    @Autowired
    private IPtUserSharePhotoDao ptUserSharePhotoDao;

    @Autowired
    private IPatientDAO patientDao;

    @Autowired
    private IMessageNotifyRecordService messageNotifyRecordService;

    @Autowired
    private DepartmentBasicService departmentBasicService;

    @Override
    public Map<String, Object> listPage(PtUserSharePhotoQueryReqDTO reqDTO, HttpServletRequest request) {
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);

        Map<String, Object> paramMap = Dict.parse(reqDTO);
        Integer  currentPage= reqDTO.getCurrentPage() == null ? 1 : reqDTO.getCurrentPage();
        Integer  pageSize = reqDTO.getPageSize() == null ? 10 : reqDTO.getPageSize();
        paramMap.put("tenantId", sessionMap.get("tenantId"));
        PageHelper.startPage(currentPage, pageSize);
        List<PtUserSharePhoto> list = ptUserSharePhotoDao.selectPage(paramMap);
        PageInfo<PtUserSharePhoto> page = new PageInfo<>(list);
        HashMap<String, Object> responseMap = MapUtil.newHashMap();
        responseMap.put("data", list);
        responseMap.put("count", page.getTotal());
        return responseMap;
    }

    @Override
    public String add(PtUserSharePhotoAddReqDTO reqDTO, HttpServletRequest request) throws Exception {
        if(StrUtil.isBlank(reqDTO.getUserId()) || CollUtil.isEmpty(reqDTO.getPhotoUrls())){
            throw new AppException("1002","参数不能为空");
        }
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String deptId = (String) sessionMap.get("deptId");
        String platType = departmentBasicService.getDepartmentBasicDetails(deptId).getPlatType();

        PtUserSharePhoto ptUserSharePhoto = new PtUserSharePhoto();
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("userId", reqDTO.getUserId());
        try {
            Patient patient= patientDao.selectById(paramMap);
            if(patient==null){
               throw new AppException("1001","新增失败");
            }
            ptUserSharePhoto.setId(IdUtil.getSnowflake(1,1).nextIdStr());
            ptUserSharePhoto.setUserId(reqDTO.getUserId());
            ptUserSharePhoto.setTenantId(sessionMap.get("tenantId").toString());
            if(CollUtil.isNotEmpty(reqDTO.getPhotoUrls())){
                ptUserSharePhoto.setPhotoUrl(CollUtil.join(reqDTO.getPhotoUrls(),","));
            }
            ptUserSharePhoto.setAccountId(patient.getAccountId());
            ptUserSharePhoto.setStatus(1);//正常
            ptUserSharePhoto.setShareTime(DateUtil.date());
            ptUserSharePhoto.setCreaterId(sessionMap.get("authorId").toString());
            ptUserSharePhoto.setCreater(sessionMap.get("authorName").toString());
            ptUserSharePhoto.setCreateTime(DateUtil.date());
            ptUserSharePhoto.setUpdateTime(DateUtil.date());
            ptUserSharePhoto.setRemark("");
            if(ptUserSharePhotoDao.insert(ptUserSharePhoto)>0){
                //发消息
                ThreadUtil.execute(()->{
                    messageNotifyRecordService.sendUserSharePhotoMessage(ptUserSharePhoto, platType);
                });

            }
        } catch (Exception e) {
            throw new AppException("1001","新增失败");
        }
        return ptUserSharePhoto.getId();
    }

    @Override
    public Map<String, Object> historyPage(PtUserSharePhotoQueryReqDTO reqDTO, HttpServletRequest request) {
        if(StrUtil.isBlank(reqDTO.getUserId()) || StrUtil.isBlank(reqDTO.getTenantId())){
            throw new AppException("1002","参数不能为空");
        }
        Map<String, Object> paramMap = Dict.parse(reqDTO);
        Integer  currentPage= reqDTO.getCurrentPage() == null ? 1 : reqDTO.getCurrentPage();
        Integer  pageSize = reqDTO.getPageSize() == null ? 10 : reqDTO.getPageSize();
        PageHelper.startPage(currentPage, pageSize);
        List<PtUserSharePhotoBO> list = ptUserSharePhotoDao.selectHistoryPage(paramMap);
        List<PtUserSharePhotoResDTO> resDTOS = list.stream().map(e->{
            PtUserSharePhotoResDTO resDTO = new PtUserSharePhotoResDTO();
            resDTO.setUserId(e.getUserId());
            resDTO.setShareTime(e.getShareTime());
            if(StrUtil.isNotBlank(e.getPhotoUrl())){
                resDTO.setPhotoUrls(Arrays.asList(e.getPhotoUrl().split(",")));
            }
            return resDTO;
        }).collect(Collectors.toList());
        PageInfo<PtUserSharePhotoBO> page = new PageInfo<>(list);
        HashMap<String, Object> responseMap = MapUtil.newHashMap();
        responseMap.put("data", resDTOS);
        responseMap.put("count", page.getTotal());
        return responseMap;
    }
}
